package com.xigua.JucOfBeautiful.chapterSix._6_2;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2022/2/1322:33
 */
public class ProductionAndComsumer {
    private static final NonReentrantLock lock = new NonReentrantLock();
    private static final Condition notFull = lock.newCondition();
    private static final Condition notEmpty = lock.newCondition();

    final static Queue<String> queue = new LinkedBlockingQueue<>();
    final static int queueSize = 10;


    public static void main(String[] args) {

        Thread producer = new Thread(()->{
           lock.lock();
           try{
               while (queue.size() == queueSize){
                   notEmpty.await();
               }
               queue.add("ele");
               notFull.signalAll();
           }catch (Exception e){
               e.printStackTrace();
           }finally {
               lock.unlock();
           }
        });

        Thread comsumer = new Thread(()->{
            lock.lock();
            try {
                while (queue.size() == 0){
                    notFull.await();
                }
                String ele = queue.poll();
                System.out.println(ele);
                notEmpty.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        });

        producer.start();
        comsumer.start();

    }
}
